package com.zsl.swing.redis.desktop.window.panel;

import com.zsl.swing.redis.desktop.model.FontSizeConfigEntity;
import com.zsl.swing.redis.desktop.model.KeyEntity;
import com.zsl.swing.redis.desktop.px.PxField;
import com.zsl.swing.redis.desktop.type.DbOptEnum;
import com.zsl.swing.redis.desktop.type.OtherMenuEnum;
import com.zsl.swing.redis.desktop.type.RedisTypeEnum;
import com.zsl.swing.redis.desktop.utils.*;
import com.zsl.swing.redis.desktop.window.ZslRedisDesktopMainWindow;
import com.zsl.swing.redis.desktop.window.dialog.ZslExpireTimeSetDialog;
import com.zsl.swing.redis.desktop.window.dialog.ZslKeyChangeDialog;
import com.zsl.swing.redis.desktop.window.menu.ZslMenuItem;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class ZslValueShowPanel extends JPanel implements ActionListener {

    private final ZslDbOptPanel parent;

    private final JTextField keyField = new PxField(400);
//    private final JTextField keyField = new JTextField(60);
    private final JTextField valField = new PxField(400);
//    private final JTextField valField = new JTextField(60);

    private final JTextArea formatArea = new JTextArea();

    private final JButton addBtn = new JButton(DbOptEnum.ADD.getText());
    private final JButton deleteBtn = new JButton(DbOptEnum.DELETE.getText());
    private final JButton updateBtn = new JButton(DbOptEnum.UPDATE.getText());

    private final JButton setExpireBtn = new JButton(DbOptEnum.SET_EXPIRE.getText());

    public ZslValueShowPanel(ZslDbOptPanel parent) {
        super();
        this.parent = parent;

        this.setLayout(new BorderLayout());

        JPanel keyPanel = new JPanel();
        keyPanel.add(new JLabel("key:"));
        keyPanel.add(this.keyField);

        JPanel valuePanel = new JPanel();
        valuePanel.add(new JLabel("val:"));
        valuePanel.add(valField);

        JPanel btnPanel = this.initBtnPanel();

        Box vBox = Box.createVerticalBox();
        vBox.add(keyPanel);
        vBox.add(valuePanel);
        vBox.add(btnPanel);

        this.keyField.setEditable(false);
        this.valField.setEditable(false);
        this.formatArea.setEditable(false);
        this.formatArea.setLineWrap(true);
        this.formatArea.setWrapStyleWord(true);
        this.formatArea.setBorder(BorderFactory.createTitledBorder("格式化展示"));
        this.formatArea.addMouseListener(this.buildMouseAdapter());

        FontSizeConfigEntity fontSizeConfig = ZslRedisDesktopMainWindow.getFontSizeConfig();
        this.formatArea.setFont(FontUtils.getFont(fontSizeConfig.getFontName(),Font.PLAIN, fontSizeConfig.getLogArea()));

        this.add(vBox,BorderLayout.NORTH);
        this.add(new JScrollPane(formatArea,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER),BorderLayout.CENTER);
        this.setVisible(true);
    }

    private MouseAdapter buildMouseAdapter(){
        return new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if(e.getButton() != MouseEvent.BUTTON3){
                    return;
                }

                String selectedText = ZslValueShowPanel.this.formatArea.getSelectedText();
                if(StringUtils.isEmpty(selectedText)){
                    return;
                }

                JPopupMenu menu = new JPopupMenu();
                menu.add(ZslMenuItem.getInstance(OtherMenuEnum.COPY.getText(), ZslValueShowPanel.this.buildCopyActionLister()));
                menu.show(ZslValueShowPanel.this.formatArea,e.getX(),e.getY());
            }
        };
    }

    private ActionListener buildCopyActionLister(){
        return event -> {
            String command = event.getActionCommand();
            if(OtherMenuEnum.COPY.getText().equals(command)){
                ZslValueShowPanel.this.formatArea.copy();
            }
        };
    }

    private JPanel initBtnPanel(){
        this.addBtn.addActionListener(this);
        this.deleteBtn.addActionListener(this);
        this.updateBtn.addActionListener(this);
        this.setExpireBtn.addActionListener(this);

        JPanel btnPanel = new JPanel();
        btnPanel.add(addBtn);
        btnPanel.add(deleteBtn);
        btnPanel.add(updateBtn);
        btnPanel.add(setExpireBtn);
        return btnPanel;
    }

    public synchronized void setRedisValue(String keyName, String keyValue) {
        this.keyField.setText(keyName);
        this.valField.setText(keyValue);

        if(!StringUtils.isEmpty(keyValue)){
            String formatValue = JsonOutUtils.formatJson(keyValue);
            int length = formatValue.length();

            ZslRedisDesktopMainWindow.getZslLogPanel().log("当前字符长度：" + length);
            if(length < 100000){
                this.formatArea.setText(formatValue);
            }else{
                int start = 0, limit = 100000;
                while(start < length){
                    this.formatArea.append(formatValue.substring(start, Math.min(start + limit, length)));
                    start += limit;
                }
            }
        }
    }

    public synchronized void clearKeyValue(String keyName) {
        String keyFieldText = this.keyField.getText();
        if(!StringUtils.isEmpty(keyFieldText) && keyFieldText.equals(keyName)){
            this.clearKeyValue();
        }
    }

    public synchronized void clearKeyValue(){
        this.keyField.setText(null);
        this.valField.setText(null);
        this.formatArea.setText(null);
    }

    public synchronized void clearKeyLike(String keyName) {
        String keyFieldText = this.keyField.getText();
        if(!StringUtils.isEmpty(keyFieldText) && keyFieldText.contains(keyName)){
            this.clearKeyValue();
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String actionCommand = e.getActionCommand();
        if(DbOptEnum.ADD.getText().equals(actionCommand)){
            ZslKeyChangeDialog.showDialog(DbOptEnum.ADD,this.parent.getEntity(),null);
        }else{
            String key = this.keyField.getText();
            if(StringUtils.isEmpty(key)){
                DialogUtils.errorDialog(ZslRedisDesktopMainWindow.getMainWindow(),"请选择key");
                return;
            }

            if(DbOptEnum.DELETE.getText().equals(actionCommand)){
                this.parent.getKeyQueryPanel().getKeyList().deleteOne(key);
            }else if(DbOptEnum.SET_EXPIRE.getText().equals(actionCommand)){
                ZslExpireTimeSetDialog.showDialog(key, this.parent.getEntity());
            }else if(DbOptEnum.UPDATE.getText().equals(actionCommand)){
                String text = this.valField.getText();
                int length = text.length();
                if(length > RedisTypeEnum.STRING.getLimit()){
                    ZslRedisDesktopMainWindow.getZslLogPanel().log("当前值长度：" + length);
                    DialogUtils.msgDialog(ZslRedisDesktopMainWindow.getMainWindow(), "当前值较大，建议命令行操作执行！");
                }else{
                    String type = RedisUtils.type(this.parent.getEntity().getUniqueId(), this.parent.getEntity().getDbIndex(), key);
                    KeyEntity keyEntity = new KeyEntity();
                    keyEntity.setKey(key);
                    keyEntity.setValue(text);
                    keyEntity.setType(type);

                    ZslKeyChangeDialog.showDialog(DbOptEnum.UPDATE, this.parent.getEntity(),keyEntity);
                }
            }

        }


    }
}
